package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.ChargeInfo;
import com.sentiment.database.bean.SysInfo;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.UserLog;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;
import com.sentiment.tools.Paging;
import com.sentiment.webcollector.net.HttpRequest;
import com.sentiment.webcollector.net.HttpResponse;

/**
 * Servlet implementation class ChargeInfoServlet
 */
@WebServlet("/ChargeInfoServlet")
public class ChargeInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doPost(request, response);		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String methodName = request.getParameter("method");
		try{
			Method method = getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 得到所有用户缴费信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetChargeList(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		List<ChargeInfo> infolist = new ArrayList<>();
		
		//连接数据库获取权限信息
		DbUtil dbutil = new DbUtil();
		dbutil.openConnection(ChargeInfo.dbName, ChargeInfo.collection);
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		List<Document> tlist = dbutil.getPage(page, 10);		
		dbutil.closeConnection();			
		ChargeInfo info = new ChargeInfo();
		for(int i = 0; i < tlist.size(); i++){
			info = new ChargeInfo(tlist.get(i));
			infolist.add(info);
		}
		long count = info.getCount();
		ObjectMapper mapper = new ObjectMapper();
		String jsonArr = mapper.writeValueAsString(infolist);
		String jsonStr = ""; 
		if(count != 0){
			jsonStr = "{\"recordsTotal\":"+ count +",\"ChargeInfo\":" + jsonArr+"}";
		}else{
			jsonStr = "{\"recordsTotal\":"+ count +",\"ChargeInfo\":" + "\"" + OperationInfo.NoChargeInfo + "\"" +"}";
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
	/**
	 * 得到某一用户缴费信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetChargeInfo(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String user_id = request.getParameter("user_id");
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		
		if(user_id.equals("myself")){
			Subject subject = SecurityUtils.getSubject();
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			if(activeUser == null){
				user_id = null;
			}else{
				user_id = activeUser.getUser_id();
			}
		}
		String jsonStr = "";
		if(user_id == null){
			jsonStr = "{\"Info\":" + "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
		
			DbUtil db = new DbUtil();
			db.openConnection(ChargeInfo.dbName, ChargeInfo.collection);
			
			ChargeInfo chargeinfo = new ChargeInfo(user_id, null, null, null, null, null, null);
			String []keys = {"user_id"};
			List<Document> tlist = db.queryMany(chargeinfo.toDocument(), keys);
			db.closeConnection();
			
			long count= tlist.size();
			tlist = Paging.paging(tlist, page, 10);
			List<ChargeInfo> chargeinfolist = new ArrayList<>();
			for (int i = 0; i < tlist.size(); i++) {
				chargeinfo = new ChargeInfo(tlist.get(i));
				chargeinfolist.add(chargeinfo);
			}
			
			ObjectMapper mapper = new ObjectMapper();
			String jsonArr = mapper.writeValueAsString(chargeinfolist);
			jsonStr = "{\"recordsTotal\":"+ count +",\"ChargeInfo\":" + jsonArr+"}";
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	/**
	 * 缴费，只向数据库中添加记录，并未更改用户权限
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Pay(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String username = request.getParameter("username");
		Double payment = Double.parseDouble(request.getParameter("payment"));
		String paydate = request.getParameter("paydate");
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String item = request.getParameter("item");
		
		User user = new User();
		user = user.getUserByUserCode(username);
		String info = "";
		String jsonStr = "";
		if(user == null){
			info = OperationInfo.UserNotFind;
		}else{
			String user_id = user.get_id();
			
			Subject subject = SecurityUtils.getSubject();
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			String operator_id = "";
			if(activeUser == null){
				jsonStr = "{\"Info\":" + "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
			}else{
				operator_id = activeUser.getUser_id();
				//向 ChargeInfo 表中添加记录
				DbUtil db = new DbUtil();
				db.openConnection(ChargeInfo.dbName, ChargeInfo.collection);
				ChargeInfo chargeinfo = new ChargeInfo(user_id, payment, Format.ToDBStrDate(paydate), Format.ToDBStrDate(startdate), Format.ToDBStrDate(enddate), item, operator_id);
				boolean insert = db.insert(chargeinfo.toDocument());
				db.closeConnection();
				
				if(insert){
					info = OperationInfo.OperSuccess;
				}else{
					info = OperationInfo.OperFailure;
				}
				jsonStr = "{\"info\":"+ "\"" + info + "\""+"}";
			}		
						
		}	
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}
	
	
	/**
	 * 按条件查询
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Query(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		String usercode = request.getParameter("username");
		String paymentStr = request.getParameter("payment");
		String paydate = request.getParameter("paydate");
		String startdate = request.getParameter("startdate");
		String enddate = request.getParameter("enddate");
		String item = request.getParameter("item");
		String operatorcode = request.getParameter("operator");
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		
		List<String> keylist = new ArrayList<>();
		String user_id = "";
		String operator_id = "";
		String info = "";
		if(!usercode.equals("")){
			User user = new User();
			user = user.getUserByUserCode(usercode);
			if(user != null){
				keylist.add("user_id");
				user_id = user.get_id();
				if(!operatorcode.equals("")){
					user = user.getUserByUserCode(operatorcode);
					if(user != null){
						keylist.add("operator_id");
						operator_id = user.get_id();
					}else{
						info = OperationInfo.NoSuchChargeInfo;
					}
				}
			}else{
				info = OperationInfo.NoSuchChargeInfo;
			}
		}
		Double payment = 0.0;
		if(!paymentStr.equals("")){
			keylist.add("payment");
			payment = Double.parseDouble(paymentStr);
		}
		if(!paydate.equals("")){
			keylist.add("paydate");
			paydate = Format.ToDBStrDate(paydate);
		}
		if(!startdate.equals("")){
			keylist.add("startdate");
			startdate = Format.ToDBStrDate(startdate);
		}
		if(!enddate.equals("")){
			keylist.add("enddate");
			enddate = Format.ToDBStrDate(enddate);
		}
		if(!item.equals("")){
			keylist.add("item");
		}
		
		List<ChargeInfo> chargeinfolist = new ArrayList<>();
		long count = 0;
		if(info == "" && keylist.size() != 0){
			
			ChargeInfo chargeinfo = new ChargeInfo(user_id, payment, paydate, startdate, enddate, item, operator_id);
			String []keys = keylist.toArray(new String [keylist.size()]);
			
			DbUtil db = new DbUtil();
			db.openConnection(ChargeInfo.dbName, ChargeInfo.collection);			
			List<Document> tlist = new ArrayList<>();
			tlist = db.queryMany(chargeinfo.toDocument(), keys);
			db.closeConnection();
			count = tlist.size();
			if(tlist.size() != 0){
				tlist = Paging.paging(tlist, page, 10);
				for (int i = 0; i < tlist.size(); i++) {
					chargeinfo = new ChargeInfo(tlist.get(i));
					chargeinfolist.add(chargeinfo);
				}
			}else{
				info = OperationInfo.NoSuchChargeInfo;
			}
			
		}
		
		String jsonStr = "";
		if(count != 0){
			ObjectMapper mapper = new ObjectMapper();
			String jsonArr = mapper.writeValueAsString(chargeinfolist);
			jsonStr = "{\"recordsTotal\":"+ count +",\"ChargeInfo\":" + jsonArr+"}";
		}else{
			jsonStr = "{\"recordsTotal\":"+ count +",\"Info\":" + "\"" +info + "\"" +"}";
		}
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
	}

}
